package com.ding.easycontroller.controller;

import com.ding.easycontroller.model.R;
import com.ding.easycontroller.pojo.ControllerBrief;
import com.ding.easycontroller.pojo.ControllerDetails;
import com.ding.easycontroller.pojo.ControllerUpdateOrAddVO;
import com.ding.easycontroller.service.ControllerService;
import com.ding.easycontroller.work.Controller;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/_config/controller")
public class _Controller {

    @Autowired
    private ControllerService controllerService;

    @PostMapping("/remove")
    public R remove(@RequestParam String id) throws IOException {
        controllerService.removeById(id);
        return R.OK;
    }

    @PostMapping("/updateOrAdd")
    public R updateOrAdd(@Validated ControllerUpdateOrAddVO controller) throws IOException {
        Controller c = new Controller();
        BeanUtils.copyProperties(controller,c);
        controllerService.updateOrAdd(c);
        return R.ok(c.getId());
    }

    @GetMapping("/get")
    R get(@RequestParam String id) { //获取脚本内容
        Controller controller = controllerService.getById(id);
        if (controller==null){return R.NotFound;}
        ControllerDetails details = new ControllerDetails();
        BeanUtils.copyProperties(controller, details);
        return R.ok(details);
    }


    @GetMapping("/all")
    R all() {
        List<Controller> controllers = controllerService.listAll();
        List<ControllerBrief> controllerBriefs = new ArrayList<>();
        for (Controller controller : controllers) {
            ControllerBrief controllerBrief = new ControllerBrief();
            BeanUtils.copyProperties(controller, controllerBrief);
            controllerBriefs.add(controllerBrief);
        }
        return R.ok(controllerBriefs);
    }

}

